﻿using Encloser.Json;
using System;
using System.Net;
using System.Text;

namespace Encloser.Toolkit
{
    public class HttpRequest
    {
        public static Result<JsonItem> Get(string url)
        {
            return Request(url);
        }

        public static Result<JsonItem> Post(string url)
        {
            return Request(url, "post");
        }

        public static Result<JsonItem> PostJson(string url, object body)
        {
            return Request(url, "post", body);
        }

        private static Result<JsonItem> Request(string url, string method = "get", object body = null)
        {
            if (string.IsNullOrEmpty(url)) return Result<JsonItem>.INVALID_PARAMETERS;
            try
            {
                var request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = method;
                request.Timeout = 10000;
                if (body != null)
                {
                    request.ContentType = "application/json";
                    using (var stream = request.GetRequestStream())
                    {
                        if (body is string)
                        {
                            var data = Encoding.UTF8.GetBytes(body as string);
                            stream.Write(data, 0, data.Length);
                        }
                        else
                        {
                            Result<JsonItem> r = null;
                            JsonParser.ToJsonStream(body, stream).Catch((msg, ex) => r = Result<JsonItem>.Failed(msg, ex));
                            if (r != null) return r;
                        }
                    }
                }
                using (var response = request.GetResponse() as HttpWebResponse)
                    using (var stream = response.GetResponseStream())
                        return JsonParser.Parse(stream);
            }
            catch (Exception e)
            {
                return Result<JsonItem>.Failed("HTTP请求失败: " + e.Message, e);
            }
        }
    }
}
